package cc.shacocloud.kotlin.tools.http

import okhttp3.Dispatcher
import okhttp3.OkHttpClient
import okhttp3.OkHttpClient.Builder
import org.jetbrains.annotations.Contract
import java.util.concurrent.TimeUnit

/**
 * @author 思追(shaco)
 */
class HttpClientBuilder {

    companion object {

        val DEFAULT: OkHttpClient = builder()
            .connectTimeout(10)
            .writeTimeout(10)
            .readTimeout(10 * 60)
            .setMaxRequests(64)
            .setMaxRequestsPerHost(5)
            .build()

        @Contract(" -> new")
        fun builder(): HttpClientBuilder {
            return HttpClientBuilder()
        }
    }

    // -----------------------

    private val clientBuilder = Builder()
    private val dispatcher = Dispatcher()

    /**
     * 设置连接超时 单位 秒
     */
    fun connectTimeout(timeout: Int): HttpClientBuilder {
        clientBuilder.connectTimeout(timeout.toLong(), TimeUnit.SECONDS)
        return this
    }

    /**
     * 设置写入超时 单位 秒
     */
    fun writeTimeout(timeout: Int): HttpClientBuilder {
        clientBuilder.writeTimeout(timeout.toLong(), TimeUnit.SECONDS)
        return this
    }

    /**
     * 设置读取超时 单位 秒
     */
    fun readTimeout(timeout: Int): HttpClientBuilder {
        clientBuilder.readTimeout(timeout.toLong(), TimeUnit.SECONDS)
        return this
    }

    /**
     * 设置最大并发数
     */
    fun setMaxRequests(max: Int): HttpClientBuilder {
        dispatcher.maxRequests = max
        return this
    }

    /**
     * 设置单域名最大并发数
     */
    fun setMaxRequestsPerHost(max: Int): HttpClientBuilder {
        dispatcher.maxRequestsPerHost = max
        return this
    }

    fun build(): OkHttpClient {
        return clientBuilder.dispatcher(dispatcher).build()
    }

}
